<template>
	<b-submit-page @submit="handleSubmit">
		<view class="p-2">
			<view class="rounded-l mb-2">
				<c-form-item title="姓名" placeholder="请输入姓名" v-model:value="formModel.consigneeName" compType="textInput" border required>
					<template #labelTextSuffix>
						<text class="hidden">空空</text>
					</template>
				</c-form-item>
				<c-form-item
					title="手机号码"
					placeholder="请输入手机号码"
					compType="textInput"
					required
					v-model:value="formModel.consigneeMobile"
					border
				></c-form-item>
				<c-form-item
					compType="select"
					selectType="area"
					title="所在地区"
					placeholder="请选择地区"
					v-model:value="regionArr"
					required
					@touch="showRegionPicker"
					border
				></c-form-item>
				<c-form-item
					compType="textarea"
					required
					title="详细地址"
					placeholder="（如**街**号）"
					v-model:value="formModel.detailAddress"
					border
				></c-form-item>
				<view class="p-3-1 text-right">
					<c-check-box v-model:value="formModel.defaulted">设为默认地址</c-check-box>
				</view>
			</view>
			<!-- <view class="bg-white rounded-l p-2">
				<view class="relative" style="min-height: 150rpx;">
					<textarea
						placeholder-style="color: #C5C6CD"
						:auto-height="true"
						class="text-n"
						v-model="identifyAddress"
						:focus="addressFocus"
						@blur="handleBlur"
					>
					</textarea>
					<view class="absolute left-0 right-0 top-0" v-if="showPlaceholder" @click="focusAddress">
						<text class="color-placeholder text-n"
							>粘贴文本可自动识别姓名、手机与地址如:张三,13800138000，广东省佛山市南海区桂城街道疏港路碧桂园广佛上城11栋505</text
						>
					</view>
				</view>
				<view class="row-center justify-end">
					<c-button size="small" type="transparent" extraClass="px-4 mr-2" @touch="clear"> 清空 </c-button>
					<c-button size="small" @touch="smartParse"> 智能识别 </c-button>
				</view>
			</view> -->
		</view>
		<!-- <c-tree-picker
			title="选择地区"
			:getData="getRegionData"
			ref="regionPickerRef"
			:fieldNames="{ key: 'code', title: 'name' }"
			@pick="handleRegionPick"
		/> -->
		<template #bottomPrefix>
			<c-button v-if="!isCreatePerson && !isCreate" @touch="handleDel" text="删除" type='transparent' extraClass="mb-2"/>
		</template>
		<c-message-dialog ref='delConfirmRef'></c-message-dialog>
	</b-submit-page>
</template>

<script>
import { ref, watch, nextTick } from 'vue';
import {
	// listRegionsByParentCode,
	saveContactAddress,
	updateContactAddress,
	deleteContactAddressById,
} from '@/base/api/contact.js';
import { verifyModelByToast } from "@/uni-sdk/utils/verify.js";

export default {
	onLoad(options) {
		const createPerson = options.createPerson;
		const from = options.from;
		this.form = from;
		const create = options.create;
		let title;
		let isCreatePerson = false;
		let isCreate = false;
		if (createPerson === '1') {
			isCreatePerson = true;
			title = '新增收货地址';
		} else if (create === '1') {
			isCreate = true;
			title = '新增收货地址';
		} else {
			title = '编辑收货地址';
			const c = this.getOpenerEventChannel();
			c.on('data', (data) => {
				if (data) {
					this.setModel(data.detail);
				}
			});
		}
		this.isCreate = isCreate;
		this.isCreatePerson = isCreatePerson;
		uni.setNavigationBarTitle({
			title,
		});
	},
	setup() {
		const isCreatePerson = ref(false);
		const isCreate = ref(true);
		const from = ref();
		/**
		 * form
		 */
		const regionArr = ref([]);
		const formModel = ref({
			consigneeName: "",
			consigneeMobile: "",
			province: "",
			city: "",
			area: "",
			detailAddress: "",
			defaulted: 0,
		});
		const rules = {
			consigneeName: {
				required: true,
				pattern: "name",
			},
			detailAddress: {
				required: true,
				requiredMes: "请输入详细地址",
			},
			consigneeMobile: {
				required: true,
				pattern: "phone",
			},
		};
		function operSuccess(){
			getApp().globalData.toast("操作成功", true);
			if(from.value){
				getApp().globalData.setUpdatePage(`pages/${from.value}/${from.value}`);
			}else{
				getApp().globalData.setUpdatePage("pages/contact-manage/contact-manage");
			}
			uni.navigateBack();
		}
		async function handleSubmit() {
			if(verifyModelByToast(formModel.value, rules)){
				if(regionArr.value.length == 0) {
					getApp().globalData.toast("请选择所在地区", true);
					return;
				}
				formModel.value.province = regionArr.value[0];
				formModel.value.city = regionArr.value[1];
				formModel.value.area = regionArr.value[2];
				formModel.value.defaulted = formModel.value.defaulted ? 1 : 0;
				let re;
				if(formModel.value.id){
					re = await updateContactAddress(formModel.value);
				}else{
					re = await saveContactAddress(formModel.value);
				}
				if(re){
					operSuccess();
				}
			}
		}
		const isDefault = ref(false);
		watch(
			isDefault,
			(v) => {
				formModel.value.isDefaultAddress = v ? 1 : 0;
			},
			{
				immediate: true,
			}
		);
		function setModel(model){
			regionArr.value = [model.province || "", model.city || "", model.area || ""];
			Object.assign(formModel.value, model);
			isDefault.value = model.isDefaultAddress === 1;
			regionData.value = {
				text: model.regionCombineName,
			};
		}
		/**
		 * region picker
		 */
		const regionPickerRef = ref();
		const regionData = ref({});
		watch(regionData, (data) => {
			if(data.value){
				//data.value: {address: "广东省佛山市顺德区兴隆十路8号", latitude: 22.980202, name: "广东申菱环境系统股份有限公司", errMsg: "chooseLocation:ok", longitude: 113.21539};
				formModel.value.detailAddress = data.value.address.replace(data.text, "") + data.value.name;
				formModel.value.regionCombineName = data.text;
			}
		});
		function showRegionPicker() {
			regionPickerRef.value.open();
		}
		async function getRegionData(node) {
			// return await listRegionsByParentCode(node ? node.code : '156');
		}
		function handleRegionPick({ keys, titles }) {
			const str = titles.join('');
			regionData.value = {
				text: str,
			};
			formModel.value.regionCombineName = str;
			formModel.value.lastRegionCode = keys[keys.length - 1];
		}
		/**
		 * identify address
		 */
		const identifyAddress = ref('');
		const showPlaceholder = ref(true);
		watch(identifyAddress, (v) => {
			showPlaceholder.value = v === '';
		});
		const addressFocus = ref(false);
		function focusAddress() {
			setTimeout(() => {
				addressFocus.value = true;
			}, 100);
		}
		function handleBlur() {
			addressFocus.value = false;
		}
		function clear(){
			identifyAddress.value = "";
		}
		function smartParse(){
			if(!identifyAddress.value){
				return;
			}
		}
		/**
		 * del
		 */
		const delConfirmRef = ref();
		function handleDel(){
			delConfirmRef.value.setOptions({
				content: "确认删除该地址吗？",
				async ok(){
					const re = await deleteContactAddressById(formModel.value.id);
					if(re){
						operSuccess();
					}
				}
			});
		}
		return {
			isDefault,
			showPlaceholder,
			addressFocus,
			focusAddress,
			handleBlur,
			isCreatePerson,
			isCreate,
			showRegionPicker,
			regionPickerRef,
			getRegionData,
			handleRegionPick,
			regionData,
			formModel,
			handleSubmit,
			identifyAddress,
			setModel,
			handleDel,
			delConfirmRef,
			from,
			smartParse,
			clear,
			regionArr,
		};
	},
};
</script>

<style lang="scss">
</style>
